package com.liang.cloud.Service.impl;

import com.liang.cloud.Dto.CartDTO;
import com.liang.cloud.Dto.OrderDTO;
import com.liang.cloud.Emun.OrderStatusEnum;
import com.liang.cloud.Emun.PayStatusEnum;
import com.liang.cloud.Emun.ResultEnum;
import com.liang.cloud.Entity.OrderDetail;
import com.liang.cloud.Entity.OrderMaster;
import com.liang.cloud.Entity.ProductInfo;
import com.liang.cloud.Exception.SellException;
import com.liang.cloud.Util.RandomUtil;
import com.liang.cloud.Converter.OrderMaster2OrderDTOConverter;
import com.liang.cloud.Feign.CartFeign;
import com.liang.cloud.Feign.ProductFeign;
import com.liang.cloud.Repository.OrderDetailRepository;
import com.liang.cloud.Repository.OrderMasterRepository;
import com.liang.cloud.Service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: 余亮亮
 * @description:
 * @create: 2019-12-29 13:24:04
 **/
@Service
@Slf4j
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    ProductFeign productFeign;
    @Autowired
    OrderDetailRepository orderDetailRepository;
    @Autowired
    OrderMasterRepository orderMasterRepository;
    @Autowired
    CartFeign cartFeign;
//    @Autowired
//    PayService payService;
//    @Autowired
//    private WebSocket webSocket;
    @Override
    @Transactional

    public OrderDTO create(OrderDTO orderDTO) {
        String orderId = RandomUtil.getUniqueKey();
        BigDecimal totalMoney = new BigDecimal(BigInteger.ZERO);
        //1.查找商品，价格要从商品里取出来，不能是前端传过来的
        for (OrderDetail orderDetail : orderDTO.getList()){
            ProductInfo productInfo = productFeign.findOne(orderDetail.getProductId());
            if (productInfo==null){
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            if (productInfo.getProductStock()< orderDetail.getProductQuantity()){
                throw new SellException(ResultEnum.PRODUCT_STOCK_NOT_ENOUGHT);
            }
            //累积计算总价
            totalMoney = totalMoney
                    .add(productInfo.getProductPrice().
                            multiply(new BigDecimal(orderDetail.getProductQuantity())));
            orderDetail.setOrderId(orderId);
            orderDetail.setDetailId(RandomUtil.getUniqueKey());
            BeanUtils.copyProperties(productInfo,orderDetail);
            orderDetailRepository.save(orderDetail);
        }
        //2.订单主表插入
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderDTO,orderMaster);
        orderMaster.setOrderAmount(totalMoney);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        orderMasterRepository.save(orderMaster);

        //3.减少库存(可以放在第一步里面，但是为了不污染，单独出来)
        List<CartDTO> list  = orderDTO.getList().stream()
                .map(e -> new CartDTO(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());
        productFeign.decreaseStore(list);

        //删除购物车
        if (orderDTO.getCartList()!=null) {
            System.out.println("11231231231");
            cartFeign.delete(orderDTO.getCartList());
        }
//        webSocket.sendMessage(orderDTO.getOrderId());
        return orderDTO;
    }

    @Override
    public OrderDTO findOne(String orderId) {
        OrderMaster orderMaster = orderMasterRepository.findByOrderId(orderId);
        if (orderMaster==null){
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetailList)) {
            throw new SellException(ResultEnum.ORDERDETAIL_NOT_EXIST);
        }

        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster,orderDTO);
        orderDTO.setList(orderDetailList);

        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findListWithOpenid(String buyerOpenid, Pageable pageable) {
        //查询出分页
        Page<OrderMaster> orderMasterPage = orderMasterRepository.findByBuyerOpenid(buyerOpenid, pageable);

        //转化为orderDTO 不过好像其中list好像没有
        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert(orderMasterPage.getContent());

        //返回一个Page的实现类（1.所需要的集合，2.分页属性 3.总数）
        return new PageImpl<OrderDTO>(orderDTOList, pageable, orderMasterPage.getTotalElements());
    }

    @Override
    public OrderDTO cancel(OrderDTO orderDTO) {

        /**
         * 订单三种状态   new  finished cancle
         * 只有新订单可以取消
         */
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
            log.error("订单状态错误:订单状态为{}",orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROE);
        }

        //更改订单状态
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO,orderMaster);
        orderMaster.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        OrderMaster resultMaster= orderMasterRepository.save(orderMaster);
        if (resultMaster==null){
            throw new SellException(ResultEnum.CANCLE_ORDER_ERROR);
        }

        //回库存
        if (CollectionUtils.isEmpty(orderDTO.getList())) {
            log.error("【取消订单】订单中无商品详情, orderDTO={}", orderDTO);
            throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
        }
        List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderDTO.getOrderId());
        List<CartDTO> cartDTOList = orderDetailList.stream()
                .map(e->new CartDTO(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());
        productFeign.addStore(cartDTOList);

        //回款
//        if (orderDTO.getPayStatus().equals(PayStatusEnum.SUCCESS.getCode())){
//            payService.refund(orderDTO);
//        }

        return orderDTO;

    }

    @Override
    @Transactional
    public OrderDTO finish(OrderDTO orderDTO) {

        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
            log.error("订单状态错误{}",orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROE);
        }

        //更改订单状态
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO,orderMaster);
        orderMaster.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        OrderMaster resultMaster= orderMasterRepository.save(orderMaster);
        if (resultMaster==null){
            throw new SellException(ResultEnum.FINISHED_ORDER_ERROR);
        }

        return orderDTO;

    }

    @Override
    @Transactional
    public OrderDTO paid(OrderDTO orderDTO) {

        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
            log.error("订单状态错误{}",orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROE);
        }
        if (!orderDTO.getPayStatus().equals(PayStatusEnum.WAIT.getCode())){
            throw new SellException(ResultEnum.ORDER_HAS_FINISHED);
        }
        //更改订单状态
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO,orderMaster);
        orderMaster.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        OrderMaster resultMaster= orderMasterRepository.save(orderMaster);
        if (resultMaster==null){
            throw new SellException(ResultEnum.FINISHED_ORDER_ERROR);
        }
        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findList(Pageable pageable) {

        Page<OrderMaster> orderMasterPage = orderMasterRepository.findAll(pageable);

        //转化为orderDTO 不过好像其中list好像没有
        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert(orderMasterPage.getContent());

        //返回一个Page的实现类（1.所需要的集合，2.分页属性 3.总数）
        return new PageImpl<OrderDTO>(orderDTOList, pageable, orderMasterPage.getTotalElements());
    }

    @Override
    public OrderDTO findOne(String openid, String orderId) {
        OrderDTO orderDTO = findOne(orderId);
        if (orderDTO.getBuyerOpenid()!=openid){
            throw new SellException(ResultEnum.ORDER_ONWER_ERROR);
        }
        return orderDTO;
    }

    @Override
    public OrderDTO cancel(String openid, String orderId) {
        OrderDTO orderDTO = findOne(orderId);
        if (orderDTO.getBuyerOpenid()!=openid){
            throw new SellException(ResultEnum.ORDER_ONWER_ERROR);
        }
        return cancel(orderDTO);
    }

    @Override
    public List<OrderDTO> findByOpenid(String openid) {
        List<OrderMaster> orderMasterList = orderMasterRepository.findByBuyerOpenidOrderByCreateTimeDesc(openid);
        List<OrderDTO> orderDTOList = orderMasterList.stream().
                map(e->{
                    OrderDTO orderDTO = new OrderDTO();
                    BeanUtils.copyProperties(e,orderDTO);
                    List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(e.getOrderId());
                    orderDTO.setList(orderDetailList);
                    return orderDTO;
                }).collect(Collectors.toList());
        return orderDTOList;
    }
}
